module sliver_read(
	input				clk_in,		//100M
	input				rst_n,
	input				SPI_SDI,
	input				CS,
	input				SPI_SCLK,
	output	reg	[15:0]	CMD,		//地址
	output	reg	[31:0]	DATA,		//数据
	output	reg			rec_over 	//接收完成
);

//*************************送入FPGA的各种数据或者信号，属于不同时钟域的，故需要做同步
reg spi_cs_0,spi_cs_1;  /* 延时两个时钟，配合检测时钟边沿 */
reg spi_sck_0,spi_sck_1;
reg spi_mosi_0,spi_mosi_1;
wire spi_cs_neg;
wire spi_sck_neg;  		//时钟下降沿读取数据
wire spi_miso_flag;

always @(posedge clk_in or negedge rst_n) begin
	if (!rst_n) begin
		{spi_cs_1,spi_cs_0}		<= 2'b11;
		{spi_sck_1,spi_sck_0}	<= 2'b00;
		{spi_mosi_1,spi_mosi_0} <= 2'b00;
	end else begin
		{spi_cs_1,spi_cs_0}		<= {spi_cs_0,CS};
		{spi_sck_1,spi_sck_0}	<= {spi_sck_0,SPI_SCLK};
		{spi_mosi_1,spi_mosi_0}	<= {spi_mosi_0,SPI_SDI};
	end
end

assign  spi_miso_flag	= spi_mosi_1; //同步后的MISO数据
assign  spi_sck_neg		= (spi_sck_1	) && (!spi_sck_0	);  /* 取下降沿 */
assign  spi_cs_neg		= (spi_cs_1		) && (!spi_cs_0		);    /* 取spi_cs下降沿，作为开始信号 */

//读取FPGA2发送的命令和数据
localparam	READY		= 4'd1;
localparam	IDLE		= 4'd2;
localparam	data_CMD	= 4'd3;
localparam	data_DATA	= 4'd4;
localparam	OVER		= 4'd5;

reg[3:0] state;
reg[7:0] cnt_CMD;
reg[7:0] cnt_data;
reg[15:0] CMD1;
reg[31:0] DATA1;

always @(posedge clk_in or negedge rst_n) begin
	if (!rst_n) begin
		state		<= READY;
		CMD			<= 16'h0;
		CMD1		<= 16'h0;
		DATA1		<= 32'h0;
		DATA		<= 32'h0;
		cnt_CMD		<= 8'd15;
		cnt_data	<= 8'd31;
		rec_over	<= 1'b0;
	end else begin
		case (state)
			READY: begin
				if (spi_cs_neg) begin
					state		<= data_CMD;
					cnt_CMD		<= 8'd15;
					cnt_data	<= 8'd31;
					rec_over	<= 1'b0;
					CMD			<= CMD;
				end else begin
					CMD1		<= 16'h0;
					DATA1		<= 32'h0;
					state		<= READY;
				end
			end
			data_CMD: begin
				if (spi_sck_neg) begin
					if (cnt_CMD > 8'd0) begin
						CMD1[cnt_CMD]	<= spi_miso_flag;
						cnt_CMD			<= cnt_CMD - 8'd1;
					end else begin
						CMD1[0]			<= spi_miso_flag;
						state			<= data_DATA;
					end
				end else begin
					state	<= data_CMD;
				end
			end
			data_DATA: begin
				if (spi_sck_neg) begin
					if (cnt_data > 8'd0) begin
						DATA1[cnt_data]	<= spi_miso_flag;
						cnt_data		<= cnt_data - 8'd1;
						CMD				<= CMD1;
					end else begin
						DATA1[0]		<= spi_miso_flag;
						state			<= OVER;
					end
				end else begin
					state	<= data_DATA;
				end
			end
			OVER: begin
				if (spi_sck_neg) begin
					state		<= READY;
					DATA		<= DATA1;
					rec_over	<= 1'b1;
					CMD			<= CMD1;
				end else begin
					state		<= OVER;
				end
			end
			default: begin
				state		<= READY;
				CMD1		<= 16'h0;
				DATA1		<= 32'h0;
				rec_over	<= 1'b0;
			end
		endcase
	end
end



endmodule
